import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
var NewCar=JSON.parse(localStorage.getItem("car"))
export default new Vuex.Store({
  state: {
    car:NewCar
  },
  mutations: {
    addInfo(state,goodsInfo){
      var flag=false
      state.car.some(item=>{
        if(item.id==goodsInfo.id){
          item.count +=goodsInfo.count
          flag=true
          return true
        }
      })
      if(!flag){
        state.car.push(goodsInfo)
      }
      localStorage.setItem("car",JSON.stringify(state.car))
    },
    goodsInfo(state,goodsInfo){
      state.car.some(item=>{
        if(item.id==goodsInfo.id){
          item.count=goodsInfo.count
          return true
        }
      })
      localStorage.setItem("car",JSON.stringify(state.car))
    },
    removeShopCar(state,goodsInfo){
      state.car.some((item,i)=>{
        if(item.id==goodsInfo){
          state.car.splice("i",1)
          return true
        }
      })
      localStorage.setItem("car",JSON.stringify(state.car))
    },
    updatedGoodsSelected(state,info) {
      state.car.some(item=>{
        if(item.id==info.id){
          item.selected=info.selected
          return true
        }
      })
      localStorage.setItem("car",JSON.stringify(state.car))
    },
  },
  getters: {
    newShuju(state){
      var count=0
      state.car.forEach(item=>{
        count+=item.count
      })
      return count
    },
    shopInfo(state){
      var obj={}
      state.car.forEach(item=>{
        obj[item.id]=item.count
      })
      return obj
    },
    shopSelected(state){
      var obj={}
      state.car.forEach(item=>{
        obj[item.id]=item.selected
      })
      return obj 
    },
    getGoodsCountAndMout(state){
      var ooo={
        count:0,//勾选的件数
        meny:0//总价格
      }
      state.car.forEach(item=>{
        if(item.selected){
          ooo.count += item.count
          ooo.meny +=item.count*item.price
        }
      })
      return ooo
    }

  }
})
